package cbfg.butil.demo

import android.app.Application
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import cbfg.butil.KLog

class MainActivity : AppCompatActivity() {
    private var currentMenuItemId = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        showFragment(R.id.actionToast)

        KLog.e(
            """
            application = $application,
            application context = $applicationContext
        """.trimIndent()
        )

        val app = (Class.forName("android.app.ActivityThread")
            .getMethod("currentApplication")
            .invoke(null, *emptyArray() ) as Application)
        KLog.e("reflect application = $app")
    }

    private fun showFragment(menuItemId: Int) {
        if (menuItemId == currentMenuItemId) {
            return
        }
        val fragment: Fragment = when (menuItemId) {
            R.id.actionToast -> ToastFragment()
            R.id.actionKLog -> KLogFragment()
            R.id.actionKKLog -> KKLogFragment()
            else -> return
        }
        supportFragmentManager.beginTransaction()
            .replace(android.R.id.content, fragment)
            .commit()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        showFragment(item.itemId)
        return true
    }
}